﻿<!DOCTYPE HTML>
<html>

<head>
   <title>二级联动列表</title>
   <meta charset="utf-8" />
   <style>
      .hide {
         display: none;
      }
   </style>


</head>

<body>
   <select name="provs">
      <option>—请选择—</option>
      <!--0-->
      <option>北京市</option>
      <!--1-->
      <option>天津市</option>
      <option>河北省</option>
   </select>

   <select name="cities" class="hide">
   </select>
   <script>
      /*实现“省”和“市”的级联下拉列表*/
      var cities = [
         [{
               "name": '东城区',
               "value": 101
            },
            {
               "name": '西城区',
               "value": 102
            },
            {
               "name": '海淀区',
               "value": 103
            },
            {
               "name": '朝阳区',
               "value": 104
            }
         ],
         [{
               "name": '河东区',
               "value": 201
            },
            {
               "name": '河西区',
               "value": 202
            },
            {
               "name": '南开区',
               "value": 303
            }
         ],
         [{
               "name": '石家庄市',
               "value": 301
            },
            {
               "name": '廊坊市',
               "value": 302
            },
            {
               "name": '保定市',
               "value": 303
            },
            {
               "name": '唐山市',
               "value": 304
            },
            {
               "name": '秦皇岛市',
               "value": 304
            }
         ]
      ];

      var sel_provs = document.getElementsByName("provs")[0];
      var sel_cities = document.getElementsByName("cities")[0];
      console.log(sel_provs);
      // var opts = sel_provs.querySelectorAll("option");
      // console.log(opts);
      sel_provs.onchange = function () {
         // for (var option of opts) {
         //    if (option.selected) {
         //       console.log(option.innerHTML);
         //    }
         // }
         var index = this.selectedIndex; //select 元素独有的属性

         if (index > 0) {
            sel_cities.className = "";
            sel_cities.innerHTML = "";

            var citys = cities[index - 1];
            for (var city of citys) {
               console.log(city.name);
               var opt = document.createElement("option");
               // opt.appendChild(document.createTextNode(city.name));
               opt.innerHTML = city.name;
               opt.value = city.value;
               console.log(opt);

               sel_cities.appendChild(opt)

            }
         } else {
            sel_cities.className = "hide";
         }



      }
   </script>
</body>

</html>